// store/modules/consultant.js
import { get, post, put, del } from '@/http/http';

const consultantModule = {
  namespaced: true,
  state: {
    consultantInfo: null, // 当前登录咨询师信息
    consultantList: [],   // 咨询师列表
    pagination: {        // 分页参数
      page: 1,
      size: 10,
      total: 0,
      search: {
        name: '',    // 姓名模糊查询
        tel: ''      // 电话模糊查询
      }
    },
    currentDialogType: 'add' // 对话框类型（add/edit）
  },
  mutations: {
    // 设置咨询师登录信息
    SET_CONSULTANT_INFO(state, info) {

      state.consultantInfo = {
      ...info,
      isCertified: info.isCertified? 1 : 0, // 1→true, 0→false
      isDisabled: info.isDisabled? 1 : 0
    }
      localStorage.setItem('consultant', JSON.stringify(info));
    },
    // 设置咨询师列表
    SET_CONSULTANT_LIST(state, { list, total }) {
      state.consultantList = list;
      state.pagination.total = total;
    },
    // 更新分页参数
    SET_PAGINATION(state, pagination) {
      state.pagination = { ...state.pagination, ...pagination };
    },
    // 设置对话框类型
    SET_DIALOG_TYPE(state, type) {
      state.currentDialogType = type;
    }
  },

  actions: {

    // 获取分页列表（带搜索）
    async fetchConsultantList({ commit, state }) {
      try {
        const { data } = await get('/hqy/consultant/search', {
          pageNum: state.pagination.page,
          pageSize: state.pagination.size,
          name: state.pagination.search.name,
          tel: state.pagination.search.tel
        });
        console.log('ccc:',data);
        
        commit('SET_CONSULTANT_LIST', {
          list: data.list,
          total: data.total
        });
      } catch (error) {
        const errMsg = this.handleError(error, '获取咨询师列表失败');
        return Promise.reject(errMsg);
      }
    },

    // 添加咨询师
    async addConsultant({ dispatch }, formData) {
      try {
        console.log("inset",formData);
        
        await post('/hqy/consultant', formData);
        await dispatch('fetchConsultantList'); // 刷新列表
        return Promise.resolve();
      } catch (error) {
        const errMsg = error.response?.data?.msg || '添加咨询师失败';
        return Promise.reject(errMsg);
      }
    },

    // 更新咨询师
    async updateConsultant({ dispatch }, { id, data }) {
      try {
        await put(`/hqy/consultant/${id}`, data);
        await dispatch('fetchConsultantList'); // 刷新列表
        return Promise.resolve();
      } catch (error) {
        const errMsg = error.response?.data?.msg || '更新咨询师信息失败';
        return Promise.reject(errMsg);
      }
    },

    // 删除咨询师
    async deleteConsultant({ dispatch }, id) {
      try {
        await del(`/hqy/consultant/${id}`);
        await dispatch('fetchConsultantList'); // 刷新列表
        return Promise.resolve();
      } catch (error) {
        const errMsg = error.response?.data?.msg || '删除咨询师失败';
        return Promise.reject(errMsg);
      }
    },

    // 统一错误处理方法
    handleError(error, defaultMsg) {
      let errorMsg = defaultMsg;
      
      if (error.response) {
        errorMsg = error.response.data.message || 
                  `服务器错误 [${error.response.status}]`;
      } else if (error.request) {
        errorMsg = '网络连接异常，请检查网络状态';
      } else {
        errorMsg = error.message;
      }
      
      console.error('请求错误:', errorMsg);
      return errorMsg;
    }
  }
};

export default consultantModule;